﻿using System.Collections.Generic;
using System.Net.Sockets;

namespace Dnsresolver
{
    internal class BufferManager
    {
        private readonly int _mBufferSize;
        private readonly Stack<int> _mFreeIndexPool;
        private readonly int _mNumBytes;
        private byte[] _mBuffer;
        private int _mCurrentIndex;

        public BufferManager(int totalBytes, int bufferSize)
        {
            _mNumBytes = totalBytes;
            _mCurrentIndex = 0;
            _mBufferSize = bufferSize;
            _mFreeIndexPool = new Stack<int>();
        }

        public void InitBuffer()
        {
            _mBuffer = new byte[_mNumBytes];
        }

        public bool SetBuffer(SocketAsyncEventArgs args)
        {
            if (_mFreeIndexPool.Count > 0)
            {
                args.SetBuffer(_mBuffer, _mFreeIndexPool.Pop(), _mBufferSize);
            }
            else
            {
                if ((_mNumBytes - _mBufferSize) < _mCurrentIndex)
                {
                    return false;
                }
                args.SetBuffer(_mBuffer, _mCurrentIndex, _mBufferSize);
                _mCurrentIndex += _mBufferSize;
            }
            return true;
        }

        public void FreeBuffer(SocketAsyncEventArgs args)
        {
            _mFreeIndexPool.Push(args.Offset);
            args.SetBuffer(null, 0, 0);
        }
    }
}